package com.vilynn.web.file;

import java.io.*;

/**
 * FileSplit
 *
 * @author Weilin Wang
 * @since 2020/5/7
 */
public class FileSplit {
    public static void main(String[] args) throws FileNotFoundException {

        String keyword = "强奸";

        String fileName = "E:\\Projects_own\\work-project\\work-project-service\\src\\main\\resources\\中华人民共和国刑法.txt";
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "GBK"))) {
            StringBuilder sb = new StringBuilder();
            while (reader.read() != -1) {
                String line = reader.readLine();

                if (line.trim().matches(".*第[一,二,三,四,五,六,七,八,九,十]+条.*")) {
                    String s = sb.toString();
                    if (s.contains(keyword)) {
                        System.out.println(s);
                    }
                    sb = new StringBuilder(line);
                } else {
                    sb.append(line);
                }
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getUTF8StringFromGBKString(String gbkStr) {
        try {
            return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new InternalError();
        }
    }

    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }
}
